import pyglet
import math
import euclid

class Infantry():
    '''Klasse Infantry

    Erstellt eine Infantry-Einheit mit speziellen Fahigkeiten
    '''
    
    def __init__(self, image="", image_marked="", x=0, y=0, s=0):
        ''' Konstruktor

        '''
        self.image = image
        self.image.anchor_x = self.image.width // 2
        self.image.anchor_y = self.image.height // 2
        self.sprite = pyglet.sprite.Sprite(self.image)
        self.image_marked = image_marked
        self.image_marked.anchor_x = self.image.width // 2
        self.image_marked.anchor_y = self.image.height // 2
        self.x = x
        self.y = y
        self.speed = s
        self.direction_v = euclid.Vector2(0, 0)
        self.destination_v = euclid.Point2()
        self.rotate = 0
        self.marked = False
        
    def setPosition(self, x, y):
        self.x = x
        self.y = y
        self.sprite.set_position(x, y)

    def getPosition(self):
        return self.x, self.y

    def setDirection(self, x, y):
        self.direction_v.x = x
        self.dircetion_v.y = y

    def setSpeed(self, s):
        self.speed = s

    def moveTo(self, x, y):
        self.sprite.rotation = math.degrees(math.atan2(y - self.y,self.x - x))
        
        tmpradian = math.radians(self.sprite.rotation)
        self.direction_v.x = -1 * math.cos(tmpradian)
        self.direction_v.y = math.sin(tmpradian)
        self.direction_v.normalize()
        
        self.destination_v.x = x
        self.destination_v.y = y

        self.speed = 20

    def mark(self):
        self.marked = True

    def unmark(self):
        self.marked = False

    def update(self, dt):
        if self.marked:
            self.sprite.image = self.image_marked
        else:
            self.sprite.image = self.image
            
        '''self.sprite.rotation += self.rotate * dt * 30
        tmpradian = math.radians(self.sprite.rotation)
        self.direction_v.x = math.cos(tmpradian)
        self.direction_v.y = -1 * math.sin(tmpradian)
        self.direction_v.normalize()'''

        if (not self.collision_sprite_point(self.destination_v.x, self.destination_v.y)):            self.setPosition(self.x + self.direction_v.x * self.speed * dt,
                             self.y + self.direction_v.y * self.speed * dt)

    def collision_sprite_point(self, p_x=0, p_y=0):

        dx = self.x - p_x
        dy = self.y - p_y

        dist = math.sqrt(dx*dx + dy*dy)

        if (dist <= self.sprite.width/2):
            return True
        
        return False

    def set_color(self, r, g, b):
        self.sprite.color = (r, g, b)

    def draw(self):
        self.sprite.draw()
        
